package com.example.springboot.config.mainifest;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import lombok.SneakyThrows;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/11/10 11:58
 */
public class MyClassFileTransformer implements ClassFileTransformer {
    @SneakyThrows
    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        // 指定转换的类名
        if (className.contains("PreJvmMainifest")) {
            ClassPool classPool = ClassPool.getDefault();
            CtClass clazz = classPool.get("com.example.springboot.controller.mainifest.PreJvmMainifest");
            // 拿到方法
            CtMethod method = clazz.getDeclaredMethod("index");
            String methodBody = "return \"hello world【version2]\";";
            // 设置内容
            method.setBody(methodBody);
            // 返回字节吗
            byte[] byteCode = clazz.toBytecode();
            // detach的意思是将内存中曾经被javassist加载过的Date对象移除，如果下次有需要在内存中找不到会重新走javassist加载
            clazz.detach();
            return byteCode;
        }
        return null;
    }
}
